/**
 * Created by PanJiaChen on 16/11/18.
 */
// 系统配置参数
import { SYSTEM_PARAMS, TO_FIXED_LIST } from '@/config/const'
import { lcStorage } from '@/utils/c_public_method.js'
import { ConvertPinyin } from '@/utils/PinYin.js'
import { ACCOUNT_BOOK } from '@/store/mutation-types'
import Vue from 'vue'
const copyList = []
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}
/**
 * 获取系统配置数据
 */
export function getSystenParams() {
  let params = lcStorage.get(SYSTEM_PARAMS)
  return params
}
/**
 * 根据系统配置名称获取配置参数值
 * @param {*} paramsName
 *
 */
export function getSystemParamsByName(paramsName) {
  let params = getSystenParams()
  let result = true
  // 获取系统配置参数中：1、单据保存后立即开新单，2、单据保存后立即审核，3、单据审核后立即开新单

  params &&
    params.forEach((item) => {
      if (item.configCode == paramsName) {
        console.log(item.configName, item.checked)
        result = item.checked
      }
    })
  return result
}
/**
 * 根据系统配置名称获取配置参数值对象
 * @param {参数名} paramsName
 *
 */
export function getSystemParamsItemByName(paramsName) {
  let params = getSystenParams()
  let result = {}
  // 获取系统配置参数中：1、单据保存后立即开新单，2、单据保存后立即审核，3、单据审核后立即开新单
  params.forEach((item) => {
    if (item.configCode == paramsName) {
      console.log(item)
      result = item
    }
  })
  return result
}

/**
 * 获取缓存中的价格金额小数点信息
 * @returns
 */
export function getToFixedListData() {
  return lcStorage.get(TO_FIXED_LIST)
}

/**
 * 格式化四位小数点
 */
export function formatFour(val) {
  let nVal = delcommafy(val)
  if (!isNaN(nVal)) {
    let result = Number(nVal)
    return result
  } else {
    return Number(0)
  }
}

/**
 * 根据系统配置信息格式化金额
 * @param {金额} val
 * @returns
 */
export function formatMoney(val) {
  let zheng = true
  let nVal = delcommafy(val)
  if (nVal < 0) {
    zheng = false
  }
  nVal = Math.abs(nVal)
  let fixedData = getToFixedListData()
  if (!fixedData) {
    fixedData = {
      allPrice: 2,
      formatAllPrice: true,
    }
  }
  if (!isNaN(nVal)) {
    let result = Number(nVal).toFixed(fixedData.allPrice)
    if (fixedData.formatAllPrice) {
      var source = String(result).split('.') //按小数点分成2部分
      source[0] = source[0].replace(new RegExp('(\\d)(?=(\\d{3})+$)', 'ig'), '$1,') //只将整数部分进行都好分割
      result = source.join('.') //再将小数部分合并进来
    }
    if (!zheng) result = '-' + result
    return result
  } else {
    return Number(0).toFixed(fixedData.allPrice)
  }
}
/**
 * 根据系统配置信息格式化价格
 * @param {价格} val
 * @returns
 */
export function formatPrice(val) {
  let fixedData = getToFixedListData()
  if (!fixedData) {
    fixedData = {
      unitPrice: 2,
      formatUnitPrice: true,
    }
  }
  let nVal = delcommafy(val)
  if (!isNaN(nVal)) {
    let result = Number(nVal).toFixed(fixedData.unitPrice)
    if (fixedData.formatUnitPrice) {
      var source = String(result).split('.') //按小数点分成2部分
      source[0] = source[0].replace(new RegExp('(\\d)(?=(\\d{3})+$)', 'ig'), '$1,') //只将整数部分进行都好分割
      result = source.join('.') //再将小数部分合并进来
    }
    return result
  } else {
    return Number(0).toFixed(fixedData.unitPrice)
  }
}
/**
 * 根据系统配置信息格式化数量
 * @param {数量} val
 * @returns
 */
export function formatNumber(val) {
  let fixedData = getToFixedListData()
  let number = 2
  number = fixedData && fixedData.number
  if (!isNaN(val)) {
    let result = Number(val).toFixed(number)
    return result
  } else {
    return Number(0).toFixed(number)
  }
}
/**
 * 去除千分位
 *@param{Object}num
 */
export function delcommafy(num) {
  if ((num + '').trim() == '' || !num) {
    return 0.0
  }
  num = String(num).replace(/,/gi, '')
  return parseFloat(num)
}

/**
 * 获取包含输入文本的供应商id
 * @param {供应商数据} list
 * @param {输入文本} text
 * @returns
 */
export function getLikeCompanyId(list, text) {
  let companyIdParam = undefined
  if (text) {
    let companyIdParamList = []
    for (let index = 0; index < list.length; index++) {
      const element = list[index]
      if (element.companyName.indexOf(text) > -1) {
        companyIdParamList.push(element.id)
      }
    }
    if (companyIdParamList.length) {
      companyIdParam = companyIdParamList.toString()
    }
  }
  return companyIdParam
}
export function getPrintCompanyInfo(list, id) {
  let accountBook = Vue.ls.get(ACCOUNT_BOOK)
  // console.log(accountBook)
  let result = {
    companyName: '',
    companyUserName: '',
    phone: '',
    address: '',
    footPhone: accountBook.phoneNumber,
    footAddress: accountBook.address,
  }
  if (id) {
    for (let index = 0; index < list.length; index++) {
      const item = list[index]
      if (item.id == id) {
        result.companyName = item.companyName
        result.companyUserName = item.companyUserName
        result.phone = item.companyPhone || item.companyLandline || ''
        result.address = `${item.provinceName || ''}${item.cityName || ''}${item.countyName || ''}${item.address || ''}`
      }
    }
  }
  return result
}

//将list数据转换为tree结构，
// 父级id字段名不传默认为pid
// 适用于tree没有新增编辑时使用
export function getTreeDataByMap(list, pid = 'pid') {
  let sourceMap = {}
  let targetMap = {}
  for (let index = 0; index < list.length; index++) {
    const element = list[index]
    let id = element.id
    sourceMap[id] = element
    targetMap[id] = element
  }
  list.forEach((item) => {
    let parent = sourceMap[item[pid]]
    if (parent) {
      if (!parent.hasOwnProperty('children') || !parent.children) {
        parent.children = []
      }
      parent.children.push(item)
      delete targetMap[item.id]
    }
  })
  let treeList = []
  for (const key in targetMap) {
    const value = targetMap[key]
    treeList.push(value)
  }
  return treeList
}

/**
 * 得到并处理缓存的系统配置的数据
 * @returns
 */
export function sysConfig() {
  let sysConfigList = lcStorage.get('sysConfigList')
  let model = {
    allow_goods_name_repeat: false,
    allow_goods_number_repeat: false,
    allow_goods_bar_code_repeat: false,
    allow_company_express_storehouse_name_repeat: false,
    allow_company_express_storehouse_number_repeat: false,
    option_company_running_account: false,
    show_shorehouse_num: false,
    show_available_num: false,
    enable_storehouse_permission_area: false,
    generate_order_number_on_save_or_verify: false,
    allow_storehouse_alarm: false,
    allow_order_overdue_alarm: false,
    sell_below_cost_alarm: false,
    allow_overdue_current_account_alarm: false,
    allow_company_credit_alarm: false,
    salesman_not_received_payment_alarm: false,
    prompt_sales_lower_cost: false,
    prompt_credit_limit: false,
    prompt_print_limit: false,
    enable_price_tracking: false,
    enable_discount_tracking: false,
    allow_multi_line_entry_goods_info: false,
    open_new_order_after_document_saved: false,
    verify_order_after_document_saved: false,
    open_new_order_after_document_verify: false,
    allow_negative_inventory: false,
    prompt_on_save: false,
    prompt_on_verify: false,
    print_after_save_sale: false,
    print_after_verify: false,
    skip_line_after_product_entry: false,
    unit_price_zero_no_prompt: false,
    show_zero_record: false,
    tax_rate: 0,
    vat_rate: 0,
    unit_price: false,
    num: false,
    price: false,
    business_statement: true,
    sales_status: true,
  }
  if (sysConfigList && sysConfigList.length > 0) {
    sysConfigList.forEach((el) => {
      if (el.code == 'tax_rate' || el.code == 'vat_rate') {
        model[el.code] = el.value
      } else {
        model[el.code] = el.value == 1 ? true : false
      }
    })
    return model
  }
  return model
}
// 判断是不是必用版
export function handleIsBaseVersion() {
  let accountVersion = Vue.ls.get('accountVersion')
  return accountVersion == '必用版'
}
// 判断是不是专业版
export function handleIsAdvancedVersion() {
  let accountVersion = Vue.ls.get('accountVersion')
  return accountVersion == '专业版'
}
// 判断当前页面是否有权限
export function handlePagePermissions(orderName) {
  let whiteList = [
    '期初库存录入',
    '期初应收应付录入',
    '期初账户余额录入',
    '期初库存',
    '期初应收应付',
    '期初账户余额',
    '期初开账/反开账',
    '订单管理',
    '账套价格设置',
    '数据恢复和反审价格设置',
    '云备份设置',
    '账套购买记录',
    '设置模板',
    '模板库',
  ]
  let highest = [ //标准财务版才有权限
    '物流代收结算单', '物流代付结算单', '物流运费结算单', '智能补货分析'
  ]
  let advanced = [ //标准财务和高级版才有权限
    '资金增加', '资金减少', '应收款增加', '应收款减少', '应付款增加', '应付款减少'
  ]
  let accountVersion = Vue.ls.get('accountVersion')
  
  if (accountVersion != '标准财务版' && highest.includes(orderName)) {
    return false
  }
  if (accountVersion == '专业版' && advanced.includes(orderName)) {
    return false
  }
  if (whiteList.includes(orderName) || orderName.includes('打印设置')) {
    return true
  }
  let userPermissionsData = lcStorage.get('userPermissions')
  if (userPermissionsData) {
    let keys = Object.keys(userPermissionsData)
    return keys.includes(orderName)
  }
  return false
}

/**
 * 得到并处理缓存的用户权限设置的数据
 * @param orderName 当前权限所属的的单据名称
 * @returns {Object} 返回的数据类型
 */
export function handlePermissions(orderName) {
  if (orderName == '往来单位') {
    orderName = '往来单位信息'
  }
  let userPermissionsData = lcStorage.get('userPermissions')
  // console.log(userPermissionsData)
  if (userPermissionsData) {
    let keys = Object.keys(userPermissionsData)
    for (let i = 0; i < keys.length; i++) {
      if (keys[i] == orderName) {
        let list = userPermissionsData[orderName]
        let buttonsPermissions = {
          ShanChu: list.indexOf('cancel') > -1,
          XiuGai: list.indexOf('edit') > -1,
          XinZeng: list.indexOf('enter') > -1,
          LuRu: list.indexOf('enter') > -1,
          DaoRu: list.indexOf('import') > -1,
          DaoChu: list.indexOf('export') > -1,
          ShenHe: list.indexOf('verify') > -1,
          ZuoFei: list.indexOf('cancel') > -1,
          HongChong: list.indexOf('red-flush') > -1,
          DaYin: list.indexOf('print') > -1,
          FenXiang: list.indexOf('share') > -1,
          FanShen: list.indexOf('de-approval') > -1,
        }
        return buttonsPermissions
      }
      // [ 权限说明
      //   "cancel”, 	作废
      //   "red-flush",	红冲
      //   "print",		打印
      //   "de-approval",	反审
      //   "import",	导入
      //   "edit", 		修改
      //   "verify", 	审核
      //   "share", 	分享
      //   "enter",		录入
      //   "export"	导出
      // ]
    }
  }
  //没有查找到权限时默认都没有权限
  return {
    ShanChu: false,
    XiuGai: false,
    XinZeng: false,
    LuRu: false,
    DaoRu: false,
    DaoChu: false,
    ShenHe: false,
    ZuoFei: false,
    HongChong: false,
    DaYin: false,
    FenXiang: false,
    FanShen: false,
  }
}

/**
 * 得到并处理缓存的用户权限设置的其他权限数据
 *
 * 补录单据、拖动分类、只可查看本部门人员所开单据、可查看其他人单据、对账后红冲、打印模板设置、单据可多次打印
 *
 * @param orderName 当前权限所属的的其他权限名称
 * @returns 返回的是否有权限
 */
export function handleOtherPerms(orderName) {
  let userPermissionsData = lcStorage.get('userPermissions')
  if (userPermissionsData) {
    if (userPermissionsData[orderName]) {
      return true
    }
  }
  //没有查找到权限时默认都没有权限
  return false
}

export function handleButtonsPermissions(data) {
  let buttonsPermissions = {
    name: data.meta.title,
  }
  for (let i = 0; i < data.buttons.length; i++) {
    let buttonName = ConvertPinyin(data.buttons[i].meta.title)
    buttonsPermissions[buttonName] = data.buttons[i].checked
  }
  return buttonsPermissions
}

/**
 * 得到并处理缓存的用户其他管理权限设置的数据
 * @param name 其他管理权限的权限名称
 * @returns {Object} 返回的数据类型
 */
export function handleOtherPermissions(name) {
  let userOtherPermissionsData = lcStorage.get('userOtherPermissions')
  if (!userOtherPermissionsData || userOtherPermissionsData.length == 0) {
    return '未找到相关权限'
  }
  for (let i = 0; i < userOtherPermissionsData.length; i++) {
    if (userOtherPermissionsData[i].name == name) {
      return userOtherPermissionsData[i].checked
    }
  }
}

export function cloneObject(obj) {
  if (obj) {
    return JSON.parse(JSON.stringify(obj))
  }
  return obj
}

// 对象转数组
export function handleObjectToArray(obj) {
  // 判断是数组直接返回
  if (obj.constructor == Array) {
    return obj
  }
  let list = []
  for (const key in obj) {
    list.push(obj[key])
  }
  return list
}
// 数组转对象
export function handleArrayToObject(list, key) {
  // 判断是对象直接返回
  if (list.constructor == Object) {
    return list
  }
  let obj = {}
  for (let i = 0; i < list.length; i++) {
    let item = list[i]
    obj[item[key]] = item
  }
  return obj
}

//获取树形结构所有子集id
export function getTreeAllSubId(data, result, includeSelf) {
  if (includeSelf) {
    result.push(data.id)
  }
  let list = data.children || []
  for (let index = 0; index < list.length; index++) {
    const item = list[index]
    result.push(item.id)
    getTreeAllSubId(item, result, false)
  }
}

export function formatHundredMillionPrice(price) {
  // console.log(price)
  let n = delcommafy(price)
  if (n >= 100000000) {
    let r = formatMoney(n / 100000000)
    return `${r}亿`
  } else {
    return formatMoney(n)
  }
}

// 获取基本单位id
export function getBasicUnitId(goodsManyNorms) {
  if (!goodsManyNorms) {
    return ''
  }
  // 只有一个数据就是基本单位
  if (goodsManyNorms.length === 1) {
    return goodsManyNorms[0].id
  }
  const unitArr = goodsManyNorms.filter((item) => item.unitType === '基本单位')
  if (unitArr && unitArr.length > 0) {
    return unitArr[0].id
  }
  return ''
}


/**
 ** 加法函数，用来得到精确的加法结果
 ** 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
 ** 调用：accAdd(arg1,arg2)
 ** 返回值：arg1加上arg2的精确结果
 **/
export function accAdd(arg1, arg2) {
  if (!arg1) arg1 = 0
  if (!arg2) arg2 = 0
  var r1, r2, m, c
  try {
    r1 = arg1.toString().split(".")[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split(".")[1].length
  } catch (e) {
    r2 = 0
  }
  c = Math.abs(r1 - r2)
  m = Math.pow(10, Math.max(r1, r2))
  if (c > 0) {
    var cm = Math.pow(10, c)
    if (r1 > r2) {
      arg1 = Number(arg1.toString().replace(".", ""))
      arg2 = Number(arg2.toString().replace(".", "")) * cm
    } else {
      arg1 = Number(arg1.toString().replace(".", "")) * cm
      arg2 = Number(arg2.toString().replace(".", ""))
    }
  } else {
    arg1 = Number(arg1.toString().replace(".", ""))
    arg2 = Number(arg2.toString().replace(".", ""))
  }
  return (arg1 + arg2) / m
}



/**
 ** 减法函数，用来得到精确的减法结果
 ** 说明：javascript的减法结果会有误差，在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
 ** 调用：accSub(arg1,arg2)
 ** 返回值：arg1加上arg2的精确结果
 **/
export function accSub(arg1, arg2) {
  if (!arg1) arg1 = 0
  if (!arg2) arg2 = 0
  var r1, r2, m, n
  try {
    r1 = arg1.toString().split(".")[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split(".")[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2)) //last modify by deeka //动态控制精度长度
  n = (r1 >= r2) ? r1 : r2
  return ((arg1 * m - arg2 * m) / m).toFixed(n)
}

/**
 ** 乘法函数，用来得到精确的乘法结果
 ** 说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
 ** 调用：accMul(arg1,arg2)
 ** 返回值：arg1乘以 arg2的精确结果
 **/
export function accMul(arg1, arg2) {
  if (!arg1) arg1 = 0
  if (!arg2) arg2 = 0
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString()
  try {
    m += s1.split(".")[1].length
  } catch (e) { }
  try {
    m += s2.split(".")[1].length
  } catch (e) { }
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}

//将后端返回的颜色尺码数据转换成前端需要的格式
export function getAttributeOrderInfoRequest(attributeGoodsResponse, transferBill = false) {
  if (!attributeGoodsResponse || attributeGoodsResponse.length == 0) {
    return []
  }
  let attributeOrderInfoRequest = []
  for (let index = 0; index < attributeGoodsResponse.length; index++) {
    let element = attributeGoodsResponse[index]
    let attributeList = element.attributeList || []
    for (let i = 0; i < attributeList.length; i++) {
      let color = attributeList[i]
      let sizeList = color.sizeList || []
      for (let j = 0; j < sizeList.length; j++) {
        let size = sizeList[j] 
        if (size.number > 0 || size.id) {
          let attributeOrderInfoRequestItem = {
            goodsId: element.id,
            colorId: color.colorId,
            sizeId: size.sizeId,
            number: size.number,
            useNumber: size.useNumber,
            id: transferBill ? '' : size.id
          }
          attributeOrderInfoRequest.push(attributeOrderInfoRequestItem)
        }
      }
    }
  }
  return attributeOrderInfoRequest
}


